package com.controller;

import com.domain.BlogArticle;
import com.domain.Statistic;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mapper.BlogArticleMapper;
import com.mapper.StatisticMapper;
import com.utils.Commons;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Controller
public class IndexController {
    @Autowired
    private BlogArticleMapper blogArticleMapper;
    @Autowired
    private StatisticMapper statisticMapper;
    @Autowired
    private Commons commons;
    //统计前10的热度文章信息
    public List<BlogArticle> getHeatArticles() {
        List<Statistic> list = statisticMapper.getStatistic();
        List<BlogArticle> articleList = new ArrayList<>();
        int i = 0;
        for (Statistic statistic : list) {
            BlogArticle article = blogArticleMapper.selectArticleWithId(statistic.getArticleId()); //根据id获取文章
            article.setHits(statistic.getHits()); //统计文章点击量
            article.setCommentsNum(statistic.getCommentsNum()); //统计文章评论量
            articleList.add(article);
            if (i++ == 9) {
                break;
            }
        }
        return articleList;
    }
    //分页查询文章列表
    public PageInfo<BlogArticle> selectArticleWithPage(Integer page, Integer count) {
        PageHelper.startPage(page, count);
        List<BlogArticle> articleList = blogArticleMapper.selectArticleWithPage();
        //封装文章统计数据
        for (BlogArticle article : articleList) {
            Statistic statistic = statisticMapper.selectStatisticWithArticleId(article.getId());
            article.setHits(statistic.getHits());
            article.setCommentsNum(statistic.getCommentsNum());
        }
        PageInfo<BlogArticle> pageInfo = new PageInfo<>(articleList);
        return pageInfo;
    }
    //博客首页，跳转文章首页
    @GetMapping(value = "/")
    public String index(Model model) {
        return this.index(model, 1, 5);
    }
    //文章页
    @GetMapping(value = "/page/{p}")
    public String index(Model model, @PathVariable("p") int page, @RequestParam(value = "count", defaultValue = "5") int count) {
//        PageHelper.startPage(page, count);
        PageInfo<BlogArticle> articles = selectArticleWithPage(page, count);
        //获取文章热度统计信息
        List<BlogArticle> articleList = getHeatArticles();
        model.addAttribute("articles", articles);
        model.addAttribute("articleList", articleList);
        return "client/index1";
    }

}
